package crp.services.api.graphql;

import crp.core.portal.app.PortalBannerService;
import crp.core.security.domain.models.Permissions;
import crp.services.api.graphql.models.CreatePortalBannerInput;
import crp.services.api.graphql.models.DeletePortalBannerInput;
import crp.services.api.graphql.models.PortalBannerPayload;
import crp.services.api.graphql.models.UpdatePortalBannerInput;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Mutation;
import org.eclipse.microprofile.graphql.Query;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

@GraphQLApi
@RequestScoped
@Transactional
public class PortalBannerGraphQLApi {
    private final PortalBannerService portalBannerService;

    @Inject
    public PortalBannerGraphQLApi(PortalBannerService portalBannerService) {
        this.portalBannerService = portalBannerService;
    }

    @Query
    @PermitAll
    @NotNull
    public List<@NotNull PortalBannerPayload> portalBanners() {
        return portalBannerService.searcher().all()
                .map(PortalBannerPayload::of).collect(Collectors.toList());
    }

    @Mutation
    @RolesAllowed(Permissions.PORTAL_BANNER_EDIT)
    @NotNull
    public PortalBannerPayload createPortalBanner(@NotNull @Valid CreatePortalBannerInput input) {
        return PortalBannerPayload.of(portalBannerService.editor().create(input.getCover(), input.getReferenceUrl()));
    }

    @Mutation
    @RolesAllowed(Permissions.PORTAL_BANNER_EDIT)
    @NotNull
    public PortalBannerPayload updatePortalBanner(@NotNull @Valid UpdatePortalBannerInput input) {
        return PortalBannerPayload.of(portalBannerService.editor().update(input.getId(), input.getCover(), input.getReferenceUrl()));
    }

    @Mutation
    @RolesAllowed(Permissions.PORTAL_BANNER_EDIT)
    @NotNull
    public boolean deletePortalBanner(@NotNull @Valid DeletePortalBannerInput input) {
        return portalBannerService.editor().deleteById(input.getId());
    }
}
